/**
 * Created by hsia on 2017/11/2.
 */
var cchartSeriesData= [],cchartCategoriesData=new Array(),tchartSeriesData= [],tchartCategoriesData=new Array();
var rangeTime;
var VehicleFlow = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

VehicleFlow.prototype={
    init:function(){
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName: 'search_btn', fs: this.findData},
            {fName: 'reset_btn', fs: this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.initOrz();
        this.initDateRange();
        this.findData();
    },
    initOrz:function () {
        var that = this;
        // 加载组织结构
        JsonpAjax(baseApiPath + 'recordMarket/ztreeData?gpcLev=wsn', '', 'json', function(res){
            var setting = {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data: {
                    key:{
                        name: "organizationName"
                    },
                    simpleData: {
                        enable:true,
                        idKey: "organizationCode",
                        pIdKey: "parentCode",
                        rootPId: ""
                    }
                }

            };
            var organizationTree = that.targetObj.find('#organization-tree3').lonixFloat({
                source : res,
                setting : setting,
                searchField : 'organizationName',
                target : that.targetObj.find('#organization_text3'),
                primary: function (nodes) {
                    if(isEmpty(nodes)){
                        return;
                    }
                    that.sysUtils.mvvmModel.set('orgName',nodes[0].organizationName);
                    that.sysUtils.mvvmModel.set('orgGpc',nodes[0].organizationTypeCode);
                    that.sysUtils.mvvmModel.set('orgCode',nodes[0].organizationCode);
                    that.targetObj.find('#organization-tree3').fadeUp();
                },
                cancel:function (nodes) {
                    if(isEmpty(nodes)){
                        return;
                    }
                    that.sysUtils.mvvmModel.set('orgName','');
                    that.sysUtils.mvvmModel.set('orgGpc','');
                    that.sysUtils.mvvmModel.set('orgCode','');
                    that.targetObj.find('#organization-tree3').fadeUp();
                }
            });
        }, true);
        that.targetObj.find("input[name=dateType]").click(function () {
            that.targetObj.find('#rangeType').empty();
            that.targetObj.find('#rangeType').append($('<input type="text" class="lonix click_float_parent k-textbox" id="rangeDateA" data-bind="value:rangeDateA"/>'));
            var type=this.value;
            var thisObj = this;
            if(this.value=='day'){
                type='date';
            }
            rangeTime = laydate.render({
                elem: '#rangeDateA'
                ,type: type
                ,show: true
                ,closeStop: thisObj
                ,theme: '#3d90da'
                ,range: '~'
            });
        });

    },
    initDateRange:function () {
        rangeTime = laydate.render({
            elem: '#rangeDateA'
            ,type: 'year'
            ,theme: '#3d90da'
            ,range: '~'
        });
        /*var that = this;
         var startChange = function () {
         var startDate = start.value(),
         endDate = end.value();

         if (startDate) {
         startDate = new Date(startDate);
         startDate.setDate(startDate.getDate());
         end.min(startDate);
         } else if (endDate) {
         start.max(new Date(endDate));
         } else {
         endDate = new Date();
         start.max(endDate);
         end.min(endDate);
         }
         }
         var endChange=function () {
         var endDate = end.value(),
         startDate = start.value();

         if (endDate) {
         endDate = new Date(endDate);
         endDate.setDate(endDate.getDate());
         start.max(endDate);
         } else if (startDate) {
         end.min(new Date(startDate));
         } else {
         endDate = new Date();
         start.max(endDate);
         end.min(endDate);
         }
         }
         var start = that.targetObj.find("#start").kendoDatePicker({
         change: startChange()
         }).data("kendoDatePicker");

         var end = that.targetObj.find("#end").kendoDatePicker({
         change: endChange()
         }).data("kendoDatePicker");

         start.max(end.value());
         end.min(start.value());*/

    },
    findData : function (e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data('that');
        }
        that.targetObj.find("#vehicleFlowTable").find("tr:not(:first)").empty();
        cchartCategoriesData=[];
        cchartSeriesData=[];
        if(validityForm(that.targetObj)){
            var param = that.sysUtils.getBindDocJson(that.bindBaseModels.bindFieldArray);
            param['dateRange']=that.targetObj.find('#rangeDateA').val();
            that.targetObj.find("input[name=dateType]").each(function () {
                if(this.checked){
                    param["dateType"]=this.value;
                }
            });
            JsonpAjax(baseApiPath+"recordMarket/vehicleFlow",JSON.stringify(param),"json",function(result){
                //构建列表
                that.initTable(result);
                //构建通道-分类小计图表
                that.createChnChart(result);
                //构建时间-通道图表
                that.createTimeChart(result,param["dateType"]);
            });

        }

    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
        rangeTime.config.elem[0].value='';
        rangeTime.config.type='year';
        that.targetObj.find("input[name=dateType]").each(function () {
            this.checked = this.value=='year'?true:false;
        })
    },
    initTable:function (obj) {
        var that = this;
        var table = that.targetObj.find("#vehicleFlowTable");
        var monthInTotal=0,monthOutTotal=0,tempInTotal=0,tempOutTotal=0,total=0;

        if(isEmptyObject(obj)){
            table.append($("<tr><td colspan='7' style='text-align:center;'>未查询到数据</td></tr>"));
        }else{
            var min=[],mout=[],tin=[],tout=[];
            for(var w in obj){
                var monthInSub=0,monthOutSub=0,tempInSub=0,tempOutSub=0,sub=0;
                var tr = $("<tr></tr>");
                var wsn=obj[w];
                var chnList = wsn.chns;
                var map = {},dest = [];
                if(!isEmpty(chnList)){
                    var chnNum = chnList.length;
                    //通道分组

                    for(var i = 0; i < chnNum; i++){
                        var chn = chnList[i];
                        if(!map[chn.chnCode]){
                            dest.push({
                                chnCode: chn.chnCode,
                                chnName: chn.chnName,
                                data: [chn]
                            });
                            map[chn.chnCode] = chn;
                        }else{
                            for(var j = 0; j < dest.length; j++){
                                var dj = dest[j];
                                if(dj.chnCode == chn.chnCode){
                                    dj.data.push(chn);
                                    break;
                                }
                            }
                        }
                    }
                    //同工作站下通道遍历
                    for(var i =0;i<dest.length;i++){

                        var chnMonthIn=0,chnMonthOut=0,chnTempIn=0,chnTempOut=0,subtotal=0;
                        if(i==0){
                            var td = $("<td rowspan='"+dest.length+"'>"+wsn["wsnName"]+"</td>");
                            tr.append(td);
                        }else{
                            tr =  $("<tr></tr>");
                        }
                        tr.append($("<td>"+dest[i]["chnName"] +"</td>"));
                        var chn = dest[i].data;
                        for(var j=0;j<chn.length;j++){
                            chnMonthIn+=chn[j]['monthIn'];
                            chnMonthOut+=chn[j]['monthOut'];
                            chnTempIn+=chn[j]['tempIn'];
                            chnTempOut+=chn[j]['tempOut'];
                        }
                        subtotal=chnMonthIn+chnMonthOut+chnTempIn+chnTempOut;
                        monthInSub+=chnMonthIn;
                        monthOutSub+=chnMonthOut;
                        tempInSub+=chnTempIn;
                        tempOutSub+=chnTempOut;

                        min.push(chnMonthIn);
                        mout.push(chnMonthOut);
                        tin.push(chnTempIn);
                        tout.push(chnTempOut);

                        monthInTotal+=chnMonthIn;
                        monthOutTotal+=chnMonthOut;
                        tempInTotal+=chnTempIn;
                        tempOutTotal+=chnTempOut;
                        sub+=subtotal;
                        total+=subtotal;
                        tr.append($("<td>"+(chnMonthIn)+"</td>"));
                        tr.append($("<td>"+(chnMonthOut)+"</td>"));
                        tr.append($("<td>"+(chnTempIn)+"</td>"));
                        tr.append($("<td>"+(chnTempOut)+"</td>"));
                        tr.append($("<td>"+(subtotal)+"</td>"));
                        table.append(tr);

                        //准备图表数据
                        cchartCategoriesData.push(dest[i]["chnName"]);
                    }
                    //小计行
                    var subtotaltr =  $("<tr style='background-color: rgba(204,255,153,.7)'></tr>");
                    subtotaltr.append($("<td colspan='2' style='text-align:right;font-weight:bold'>小计：</td>"));
                    subtotaltr.append($("<td>"+(monthInSub)+"</td>"));
                    subtotaltr.append($("<td>"+(monthOutSub)+"</td>"));
                    subtotaltr.append($("<td>"+(tempInSub)+"</td>"));
                    subtotaltr.append($("<td>"+(tempOutSub)+"</td>"));
                    subtotaltr.append($("<td>"+(sub)+"</td>"));
                    table.append(subtotaltr);
                }
            }
            //总计行
            var totalLastTr = $("<tr style='background-color: rgba(153,205,255,.7)'></tr>");
            totalLastTr.append($("<td colspan='2' style='text-align:right;font-weight:bold'>合计：</td>"));
            totalLastTr.append($("<td>"+(monthInTotal)+"</td>"));
            totalLastTr.append($("<td>"+(monthOutTotal)+"</td>"));
            totalLastTr.append($("<td>"+(tempInTotal)+"</td>"));
            totalLastTr.append($("<td>"+(tempOutTotal)+"</td>"));
            totalLastTr.append($("<td>"+(total)+"</td>"));
            table.append(totalLastTr);

            cchartSeriesData.push({name:'月卡入场',data:min});
            cchartSeriesData.push({name:'月卡出场',data:mout});
            cchartSeriesData.push({name:'临卡入场',data:tin});
            cchartSeriesData.push({name:'临卡入场',data:tout});
        }

    },
    createChnChart:function (obj) {
        var that = this;
        that.targetObj.find("#chnChart").kendoChart({

            title: {
                text: "通行凭证进出通道场次统计"
            },
            legend: {
                position: "top"
            },
            chartArea: {
                background: ""
            },
            seriesDefaults: {
                type: "line"
            },
            series: cchartSeriesData,
            categoryAxis: {
                categories: cchartCategoriesData,
                majorGridLines: {
                    visible: false
                },
                labels: {
                    rotation: "auto"
                },
                crosshair: {
                    visible: true
                }
            },

            valueAxis: {
                type: "log",
                labels: {
                    format: "N0"
                },
                minorGridLines: {
                    visible: true
                },
            },
            tooltip: {
                visible: true,
                shared: true,
                format: "N0"
            }
        });
    },
    createTimeChart:function (obj,dateType) {
        var that = this;
        that.cosmeticData(obj,dateType);
        that.targetObj.find("#timeChart").kendoChart({
            title: {
                text: "按时段进出场次统计图表"
            },
            legend: {
                position: "bottom"
            },
            chartArea: {
                background: ""
            },
            seriesDefaults: {
                type: "line",
                style: "smooth"
            },
            series: tchartSeriesData,
            valueAxis: {
                labels: {
                    format: "N0"
                },
                line: {
                    visible: false
                },
                axisCrossingValue: -10
            },
            categoryAxis: {
                categories: cchartCategoriesData,
                majorGridLines: {
                    visible: false
                },
                labels: {
                    rotation: "auto"
                }
            },
            tooltip: {
                visible: true,
                format: "N0",
                template: "#= series.name #: #= value #"
            }
        });
    },
    cosmeticData:function (obj,dateType) {
        if(!isEmptyObject(obj)){
            tchartCategoriesData=[];
            tchartSeriesData=[];
            var subDate=[];
            var subLength=10;
            if('month'==dateType){
                subLength=7;
            }else if('year'==dateType){
                subLength=4;
            }
            //取出所有时间单位数据并去重
            //定义数组去重函数
            Array.prototype.lonixUnique = function(){
                var res = [];
                var json = {};
                for(var i = 0; i < this.length; i++){
                    if(!json[this[i]]){
                        res.push(this[i]);
                        json[this[i]] = 1;
                    }
                }
                return res;
            }
            var timeArray=new Array();
            var chnArray=new Array();
            var allChn =[];


            for(var w in obj){
                var wsn=obj[w];
                var chnList = wsn.chns;
                if(!isEmpty(chnList)){
                    var chnNum = chnList.length;
                    //通时间单位通道遍历
                    for(var i =0;i<chnNum;i++){
                        allChn.push(chnList[i]);
                    }
                }
            }
            var map = {},dest = [];
            for(var c=0;c<allChn.length;c++){
                var chn=allChn[c];
                var subTime=chn.countDate.substr(0,subLength);
                timeArray.push(subTime);
                chnArray.push(chn.chnName+","+chn.chnCode);
                if(!map[subTime]){
                    dest.push({
                        subTime: subTime,
                        data: [chn]
                    });
                    map[subTime] = chn;
                }else{
                    for(var j = 0; j < dest.length; j++){
                        var dj = dest[j];
                        if(dj.subTime == chn.countDate.substr(0,subLength)){
                            dj.data.push(chn);
                            break;
                        }
                    }
                }
            }

            chnArray=chnArray.lonixUnique(chnArray);
            timeArray=timeArray.lonixUnique(timeArray);
            //遍历通道
            for(var c=0;c<chnArray.length;c++){
                var objact = chnArray[c].split(",");
                var code = objact[1];
                var timeDate=[];

                //遍历时间单位分组数据
                for(var i =0;i<dest.length;i++){
                    var list = dest[i].data;
                    var subTotal=0;
                    var has=false;
                    //遍历同时间单位通道数据
                    for(var k=0;k<list.length;k++){
                        var chnObj=list[k];
                        //校验时间分组是否包含指定通道数据
                        if(chnObj.chnCode==code){
                            has=true;
                            subTotal+=(chnObj['monthIn']+chnObj['monthOut']+chnObj['tempIn']+chnObj['tempOut']);
                        }
                    }
                    if(has){
                        timeDate.push(subTotal);
                    }else{
                        timeDate.push(0);
                    }
                }
                tchartSeriesData.push({name:objact[0],data:timeDate});

            }
            cchartCategoriesData=timeArray;
        }
    }
}